package ar.edu.unlu.sistemas.p2p.business.net;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

import ar.edu.unlu.sistemas.p2p.business.net.tcp.TCPListener;
import ar.edu.unlu.sistemas.p2p.business.net.udp.UDPListener;
import ar.edu.unlu.sistemas.p2p.business.util.Params;

public class ProtocolListenerController {

	public static final String TCP = "TCP";
	public static final String UDP = "UDP";
	public static int TCP_PORT = 3600;
	public static int UDP_PORT = 4600;
	
	private static ProtocolListenerController INSTANCE;
	
	private HashMap<String,ProtocolListener> listeners;
	
	private ProtocolListenerController() {
		this.setListeners(new HashMap<String,ProtocolListener>());
		//this.addListener(TCP);
		//this.addListener(UDP);
	}

	public HashMap<String,ProtocolListener> getListeners() {
		return listeners;
	}

	private void setListeners(HashMap<String,ProtocolListener> listeners) {
		this.listeners = listeners;
	}

	public static ProtocolListenerController getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new ProtocolListenerController();
		}
		return INSTANCE;
	}

	public synchronized void removeListener (String keyProtocol) {
		if (this.getListeners().containsKey(keyProtocol)) {
			this.getListeners().remove(keyProtocol).close();
		}
	}
	
	public synchronized ProtocolListener addListener (String keyProtocol) {
		ProtocolListener listener = null;
		if (!this.getListeners().containsKey(keyProtocol)) {
				if (TCP.equals(keyProtocol)) {
					try {
						listener = new TCPListener(Params.TCP_LISTEN_PORT);
						this.getListeners().put(TCP, listener);
					} catch (Exception e) {
					}
				} else if (UDP.equals(keyProtocol)) {
					try {
						listener = new UDPListener(UDP_PORT);
						this.getListeners().put(UDP, listener);
					} catch (Exception e) {
					}
				}					
		}
		return listener;
	}
	
	public synchronized ProtocolListener getListener (String keyProtocol) {
		ProtocolListener pl = null;
		if (this.getListeners().containsKey(keyProtocol)) {
				pl = this.getListeners().get(keyProtocol);
		}
		return pl;
	}
	
	public synchronized void stopAllListeners() {
		CopyOnWriteArraySet<String> keySet = new CopyOnWriteArraySet<String>(this.getListeners().keySet());
		Iterator<String> it = keySet.iterator();
		while (it.hasNext()) {
			this.removeListener(it.next());
		}
	}
	
}


